<template>
<!-- 容器盒子 -->
  <div class="login-container">
    <!-- 注册区域盒子 -->
    <div class="login-box">
      <!-- 标题背景图盒子 使用背景图图片无法选中 体验感好些 -->
      <div class="title-box"></div>
      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="btnLogin" type="primary" @click="login">登陆</el-button>
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// import axios from 'axios'
import { loginApi } from '@/api/user.js'
export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名必须是1-10的字母数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15的非空字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return

        // const { data: res } = await axios({
        //   method: 'post',
        //   url: 'http://www.liulongbin.top:3008/api/login',
        //   data: this.loginForm
        // })
        const { data: res } = await loginApi(this.loginForm)

        console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$store.commit('user/updateToken', res.token)
        this.$router.push('/')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  height: 100%;
  background: url('../assets/images/login_bg.jpg') no-repeat;
  background-size: cover;

  .login-box {
    box-sizing: border-box;
    padding: 0 20px;
    width: 400px;
    height: 270px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .title-box {
      height: 60px;
      background: url('../assets/images/login_title.png') center no-repeat;
    }
  }
  .btnLogin {
    width: 100%;
  }
}
</style>
